package com.zp.base.admin.controller;

import java.util.*;

import com.zp.base.admin.vo.UserVo;
import com.zp.base.admin.common.annotation.AddGroup;
import com.zp.base.admin.common.annotation.UpdateGroup;
import com.zp.base.admin.common.aspect.AddOperatorLog;
import com.zp.base.admin.common.constant.BizCodeEnum;
import com.zp.base.admin.common.utils.PageUtils;
import com.zp.base.admin.common.utils.R;
import com.zp.base.admin.common.utils.ValidUtil;
import com.zp.base.admin.config.SiteConfig;
import com.zp.base.admin.entity.RoleEntity;
import com.zp.base.admin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zp.base.admin.service.UserService;



/**
 * 
 *
 * @author zhangpeng
 * @email zhangpeng@aliyun.com
 * @date 2021-02-28 11:15:56
 */
@Controller
@RequestMapping("admin/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private SiteConfig siteConfig;


    /**
     * 列表
     * @return
     */
    @RequestMapping("/list")
    @AddOperatorLog(content = "查看了用户列表")
    @PreAuthorize("hasAuthority('user:list')")
    public String list(@RequestParam(name = "username", defaultValue = "") String username,
                       @RequestParam(name = "currentPage", defaultValue = "1") String page,
                       @RequestParam(name = "limit", defaultValue = "5") String limit,Model model){
        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pageUtils = userService.queryPage(params);

        model.addAttribute("pageBean", pageUtils);
        model.addAttribute("title","用户列表");
        model.addAttribute("username",username);
        model.addAttribute("siteName", siteConfig.getSiteName());
        return "admin/user/list";
    }

    @GetMapping("/add")
    @PreAuthorize("hasAuthority('user:add')")
    public String toAdd(Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<RoleEntity> roleEntities = roleService.list();

        model.addAttribute("roles", roleEntities);
        model.addAttribute("title","用户列表");
        model.addAttribute("siteName", siteConfig.getSiteName());
        return "admin/user/add";
    }

    /**
     * 保存
     */
    @PostMapping("/add")
    @AddOperatorLog(content = "添加了用户")
    @ResponseBody
    @PreAuthorize("hasAuthority('user:add')")
    public R save(@Validated({AddGroup.class}) UserVo addUserVo, BindingResult bindingResult){
        //检查菜单信息  使用JSR303校验
        if (bindingResult.hasErrors()) {
            return ValidUtil.getErrorInfo(bindingResult);
        }
        //判断用户名是否存在
        boolean exists = userService.usernameIsExists(addUserVo.getUsername(), -1);
        if (exists) {
            return R.error(BizCodeEnum.USERNAME_IS_EXISTS.getCode(), BizCodeEnum.USERNAME_IS_EXISTS.getMsg());
        }

        addUserVo.setCreateTime(new Date());
        addUserVo.setUpdateTime(new Date());

        boolean save = userService.addUser(addUserVo);
        if (!save) {
            return R.error(BizCodeEnum.ADD_USER_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.ADD_USER_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 去修改页面
     */
    @GetMapping("/edit")
    @PreAuthorize("hasAuthority('user:edit')")
    public String toEdit(@RequestParam(name = "id")Long id, Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<RoleEntity> roleEntities = roleService.list();

        model.addAttribute("title","用户列表");
        model.addAttribute("roles", roleEntities);
        model.addAttribute("siteName", siteConfig.getSiteName());
        UserVo userVo = userService.selectByUserId(id);
        model.addAttribute("user", userVo);
        return "admin/user/edit";
    }

    /**
     * 修改
     */
    @PostMapping("/edit")
    @AddOperatorLog(content = "修改了用户信息")
    @ResponseBody
    @PreAuthorize("hasAuthority('user:edit')")
    public R edit(@Validated(UpdateGroup.class) UserVo updateUserVo, BindingResult bindingResult){
        //检查菜单信息  使用JSR303校验
        if (bindingResult.hasErrors()) {
            return ValidUtil.getErrorInfo(bindingResult);
        }
        //判断用户名是否存在
        boolean exists = userService.usernameIsExists(updateUserVo.getUsername(), updateUserVo.getId());
        if (exists) {
            return R.error(BizCodeEnum.USERNAME_IS_EXISTS.getCode(), BizCodeEnum.USERNAME_IS_EXISTS.getMsg());
        }

        updateUserVo.setUpdateTime(new Date());
        boolean update = userService.updateUser(updateUserVo);
        if (!update) {
            return R.error(BizCodeEnum.UPDATE_USER_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.UPDATE_USER_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @AddOperatorLog(content = "删除了菜单")
    @ResponseBody
    @PreAuthorize("hasAuthority('user:delete')")
    public R delete(@RequestParam(name = "id")Long id){
        if (id == null) {
            return R.error(BizCodeEnum.DELETE_USER_ID_NOT_NULL.getCode(), BizCodeEnum.DELETE_USER_ID_NOT_NULL.getMsg());
        }
        //删除菜单
        boolean b = userService.deleteByUserId(id);
        if (!b) {
            return R.error(BizCodeEnum.DELETE_USER_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.DELETE_USER_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

}
